<!--
 * @Description: 
 * @Version: 1.0.1
 * @Autor: hrlu.cn
 * @Date: 2022-06-27 21:44:06
 * @LastEditors: hrlu.cn
 * @LastEditTime: 2022-06-29 21:55:22
-->
{% extends "base.html" %}

{% block cssextend %}
    <link href="/assets/vendor/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="/assets/css/bootstrap-table-custom.css" rel="stylesheet">
{% endblock %}

{% block cssstyle %}
{% endblock %}

{% block content %}
     <!-- DATA TABLE-->
     <section class="p-t-20">
        <div class="container">
            <div class="row">
                <div class="col-lg-6">
                    <!-- TOP CAMPAIGN-->
                    <div class="statistic-chart-1" style="padding-right: 20px;">
                        <h3 class="title-3 m-b-10">WIND概念板块情况</h3>
                        <table id="wind-concepts-table" class="table table-top-campaign">
                            <thead>
                                <tr>
                                    <th data-align="center" data-field="row_no" data-sortable="true">序号</th>
                                    <th data-align="center" data-field="cname" data-sortable="true">名称</th>
                                    <th data-align="center" data-field="stock_count" data-sortable="true">成分股个数</th>
                                    <th data-align="center" data-field="stocks_list" data-formatter="textOverFlowDisplay">详情</th>
                                    <th data-align="center" data-field="previous_stock_count" data-sortable="true">上期个数</th>
                                    <th data-align="center" data-field="previous_stocks_list" data-formatter="textOverFlowDisplay" style="color: #666">上期详情</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="col-lg-6">
                    <!-- TOP CAMPAIGN-->
                    <div class="statistic-chart-1" style="padding-right: 20px;">
                        <h3 class="title-3 m-b-10">Tushare概念板块情况</h3>
                        <table id="tushare-concepts-table" class="table table-top-campaign">
                            <thead>
                                <tr>
                                    <th data-align="center" data-field="row_no" data-sortable="true">序号</th>
                                    <th data-align="center" data-field="cname" data-sortable="true">名称</th>
                                    <th data-align="center" data-field="stock_count" data-sortable="true">成分股个数</th>
                                    <th data-align="center" data-field="stocks_list" data-formatter="textOverFlowDisplay">详情</th>
                                    <th data-align="center" data-field="previous_stock_count" data-sortable="true">上期个数</th>
                                    <th data-align="center" data-field="previous_stocks_list" data-formatter="textOverFlowDisplay" style="color: #666">上期详情</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="statistic-chart-1">
                        <h3 class="title-3 m-b-10">Tushare概念板块营收情况</h3>
                        <table id="qcpt-table" class="table table-hover">
                            <thead>
                                <tr>
                                    <th data-align="center" data-field="concept_code" data-sortable="true">概念代码</th>
                                    <th data-align="center" data-field="concept_name" data-sortable="true">概念名称</th>
                                    <th data-align="center" data-field="stock_basic_count" data-sortable="true">成分个数</th>

                                    <th data-align="center" data-field="revenue" data-sortable="true">营业收入</th>
                                    <th data-align="center" data-field="revenue_yoy" data-sortable="true">营收同比增长</th>
                                    <th data-align="center" data-field="revenue_top3" data-sortable="true">营收前三占比</th>
                                    <th data-align="center" data-field="revenue_top5" data-sortable="true">营收前五占比</th>

                                    <th data-align="center" data-field="profit_dedt" data-sortable="true">扣非后净利润</th>
                                    <th data-align="center" data-field="profit_dedt_yoy" data-sortable="true">扣非同比增长</th>

                                    <!--th data-align="center" data-field="revenue_qoq" data-sortable="true">营收环比增长</th>
                                    
                                    <th data-align="center" data-field="profit_dedt_top3" data-sortable="true">扣非前三占比</th>
                                    <th data-align="center" data-field="profit_dedt_top5" data-sortable="true">扣非前五占比</th>
                                    <th data-align="center" data-field="profit_dedt_qoq" data-sortable="true">扣非环比增长</th>
                                    
                                    <th data-align="center" data-field="net_profit_fy1" data-sortable="true">FY1总净利润</th>
                                    <th data-align="center" data-field="fy1_to_fy0" data-sortable="true">FY1同比增长</th>
                                    <th data-align="center" data-field="net_profit_fy2" data-sortable="true">FY2总净利润</th>
                                    <th data-align="center" data-field="fy2_to_fy1" data-sortable="true">FY2同比增长</th-->
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <div id="qcpt-toolbar">
        <div class="input-group">
            <div id="filter-quarter">
                <select class="form-control form-control-sm" tabindex="-1" name="quarter" id="quarterSelect">
                    {% for p in periods %}
                        <option value="{{ p }}">{{ p }}</option>
                    {% endfor %}
                </select>
            </div>
        </div>
    </div>

    <div class="modal fade" id="detail-modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-wide">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">历史数据</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <table id="qcpt-table-detail" class="table table-hover">
                        <thead>
                            <tr>
                                <th data-align="center" data-field="quarter" data-sortable="true">统计季度</th>

                                <th data-align="center" data-field="revenue" data-sortable="true">营业收入</th>
                                
                                <th data-align="center" data-field="revenue_yoy" data-sortable="true">营收同比增长</th>
                                <th data-align="center" data-field="revenue_top3" data-sortable="true">营收前三占比</th>
                                <th data-align="center" data-field="revenue_top5" data-sortable="true">营收前五占比</th>
                                <th data-align="center" data-field="profit_dedt" data-sortable="true">扣非后净利润</th>
                                <th data-align="center" data-field="profit_dedt_yoy" data-sortable="true">扣非同比增长</th>

                                <!--th data-align="center" data-field="revenue_qoq" data-sortable="true">营收环比增长</th>
                                
                                <th data-align="center" data-field="profit_dedt_top3" data-sortable="true">扣非前三占比</th>
                                <th data-align="center" data-field="profit_dedt_top5" data-sortable="true">扣非前五占比</th>
                                <th data-align="center" data-field="profit_dedt_qoq" data-sortable="true">扣非环比增长</th>
                                
                                <th data-align="center" data-field="net_profit_fy1" data-sortable="true">FY1总净利润</th>
                                <th data-align="center" data-field="fy1_to_fy0" data-sortable="true">FY1同比增长</th>
                                <th data-align="center" data-field="net_profit_fy2" data-sortable="true">FY2总净利润</th>
                                <th data-align="center" data-field="fy2_to_fy1" data-sortable="true">FY2同比增长</th-->
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div id="wind-concepts-toolbar">
        <div class="input-group">
            <select class="form-control form-control-sm" style="width: 108px;" tabindex="-1" name="trade_date" id="windConceptsDateSelect">
                {% for p in wind_update_date_list %}
                    <option value="{{ p | date:"Y-m-d" }}">{{ p | date:"Y-m-d" }}</option>
                {% endfor %}
            </select>
                    
            <button class="form-control form-control-sm" onclick="document.getElementById('windConceptFileChoice').click()">
                <i class="fas fa-upload m-r-10"></i>
            </button>
            <input type="file" id="windConceptFileChoice" style="display: none;"!>
            <!--button class="form-control form-control-sm" onclick="initializeCombinedKeywords()">配置关键词</button-->
            <span id="wind-concepts-info" class="m-t-5 m-l-10"></span>
        </div>
        <div class="input-group">
        </div>
    </div>
    <div id="tushare-concepts-toolbar">
        <div class="input-group">
            <select class="form-control form-control-sm" tabindex="-1" name="trade_date" id="tushareConceptsDateSelect">
                {% for p in tushare_update_date_list %}
                    <option value="{{ p | date:"Y-m-d" }}">{{ p | date:"Y-m-d" }}</option>
                {% endfor %}
            </select>
            <span id="tushare-concepts-info" class="m-t-5 m-l-10"></span>
        </div>
    </div>
    <div class="modal fade" id="windConceptModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">上传Wind概念板块</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <table class="table bootstrap-table" id="windConceptModalTable">
                        <thead>
                            <tr>
                                <th data-align="center" data-field="证券代码">证券代码</th>
                                <th data-align="center" data-field="证券简称">证券简称</th>
                                <th data-align="center" data-field="所属概念板块" data-formatter="textOverFlowDisplay">所属概念板块</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    {% csrf_token %}
                    <button type="button" class="btn btn-sm btn-primary" data-dismiss="modal" onclick="uploadWindConcept()">提交</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block jsextend %}
    <script src="/assets/vendor/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="/assets/vendor/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>

    <script src="/assets/vendor/tableexport/tableExport.min.js"></script>
    <script src="/assets/vendor/bootstrap-table/bootstrap-table-export.min.js"></script>
    <!--script src="/assets/vendor/jspdf/jspdf.min.js"></script>
    <script src="/assets/vendor/jspdf/jspdf.plugin.autotable.js"></script-->
    <script src="/assets/js/echarts.min.js"></script>
    <script src="/assets/vendor/sheetjs/xlsx.full.min.js"></script>
{% endblock %}

{% block jsscript %}
<script>
    var periodChoices = {{ periods | safe }};
    var argChoices = [];
    var updateUrl = function (filter = false) {
        tableOption.url = '/api/quarter_concept_data?quarter=' + $('#quarterSelect').val();
        $('#qcpt-table').bootstrapTable('refreshOptions', tableOption);
    }

    var tableOption = {
        url: '/api/quarter_concept_data?quarter=' + $('#quarterSelect').val(),
        responseHandler: function (res, jqXHR) {
            for (var idx in res.rows) {
                var row = res.rows[idx];
                row.fy1_to_fy0 = 10000 * row.net_profit_fy1 / row.net_profit_fy0 - 1;
                row.fy2_to_fy1 = row.net_profit_fy2 / row.net_profit_fy1 - 1;

                ['revenue', 'profit_dedt'].forEach(function (field) {
                    row[field] = digitFormatter(row[field], 'CNY');
                });

                ['net_profit_fy1', 'net_profit_fy2',].forEach(function (field) {
                    row[field] = digitFormatter(row[field] * 10000, 'CNY');
                });

                ['revenue_top3', 'revenue_top5', 'revenue_yoy', 'revenue_qoq',
                 'profit_dedt_top3', 'profit_dedt_top5', 'profit_dedt_yoy', 
                 'profit_dedt_qoq', 'fy1_to_fy0', 'fy2_to_fy1'
                ].forEach(function (field) {
                    row[field] = digitFormatter(row[field], 'percentage');
                }); 

                ['revenue_yoy', 'revenue_qoq', 'profit_dedt_yoy', 
                'profit_dedt_qoq', 'fy1_to_fy0', 'fy2_to_fy1'].forEach(function (field) {
                    row[field] = dyeingFormatter(row[field]);
                }); 
            }
            return res;
        },
        onClickRow: function (row, elem, field) {
            detailTableOption.url = '/api/quarter_concept_data?sort=-quarter&stock_concept=' + row.stock_concept_id;
            $('#qcpt-table-detail').bootstrapTable('refreshOptions', detailTableOption);

            $('#detail-modal').modal('toggle');
        },
        align: 'center',
        search: true,
        showRefresh: true,
        showColumns: true,
        iconSize: 'sm',

        classes: 'table',
        toolbar: '#qcpt-toolbar',

        sortable: true,
        serverSort: true,
        sortName: 'revenue',
        sortOrder: 'desc',

        pagination: true,
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],

        showExport: true,
        exportDataType: '',
        exportTypes: ['json', 'csv', 'txt', 'sql', 'excel'], //  'pdf', 'xml', 
    };

    var detailTableOption = {
        responseHandler: tableOption.responseHandler,
        align: 'center',
        classes: 'table',
        iconSize: 'sm',

        pagination: true,
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],
    };

    var windTableOption = {
        updateUrl: function () { this.url = '/api/stock_concept_history_data?source=2&update_date=' + $('#windConceptsDateSelect').val()},

        responseHandler: function (res, jqXHR) {
            res.info = res.info ? res.info : {concept_count: 0, add_count: 0, reduce_count: 0};
            $('#wind-concepts-info').text(`
                板块数量: ` + res.info.concept_count + ` 新增数量: ` + res.info.add_count + ` 剔除数量: ` + res.info.reduce_count + `
            `);

            for (var idx in res.rows) {
                var row = res.rows[idx];
                row['row_no'] = idx;

                ['stocks_list', 'previous_stocks_list'].forEach( function (field) {
                    var stocks = [];
                    for (var jdx in row[field]) {
                        stocks.push(row[field][jdx]['name']);
                    }
                    row[field] = stocks.join('/');
                })
            }
            return res; 
        },
        align: 'center',

        classes: 'table',
        toolbar: '#wind-concepts-toolbar',

        sortable: true,
        serverSort: true,

        pagination: true,
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],

        onPostBody: function(data) {$("[data-toggle='popover']").popover();},
        formatShowingRows: function(pageFrom, pageTo, totalRows) {return '总共 ' + totalRows + ' 条记录'},
    };

    var tushareTableOption = {
        updateUrl: function () { this.url = '/api/stock_concept_history_data?source=1&update_date=' + $('#tushareConceptsDateSelect').val()},

        responseHandler: function (res, jqXHR) {
            res.info = res.info ? res.info : {concept_count: 0, add_count: 0, reduce_count: 0};
            $('#tushare-concepts-info').text(`
                板块数量: ` + res.info.concept_count + ` 新增数量: ` + res.info.add_count + ` 剔除数量: ` + res.info.reduce_count + `
            `);

            for (var idx in res.rows) {
                var row = res.rows[idx];
                row['row_no'] = parseInt(idx) + 1;
                ['stocks_list', 'previous_stocks_list'].forEach( function (field) {
                    var stocks = [];
                    for (var jdx in row[field]) {
                        stocks.push(row[field][jdx]['name']);
                    }
                    row[field] = stocks.join('/');
                })
            }
            return res; 
        },
        align: 'center',

        classes: 'table',
        toolbar: '#tushare-concepts-toolbar',

        sortable: true,
        serverSort: true,

        pagination: true,
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],

        onPostBody: function(data) {$("[data-toggle='popover']").popover();},
        formatShowingRows: function(pageFrom, pageTo, totalRows) {return '总共 ' + totalRows + ' 条记录'},
    };

    
    var windConceptUploadTableOption = {
        data: [],
        align: 'center',
        classes: 'table',
        // search: true,
        pagination: true,
        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],
        onPostBody: function(data) {$("[data-toggle='popover']").popover();},
        formatShowingRows: function(pageFrom, pageTo, totalRows) {return '总共 ' + totalRows + ' 条记录'},
    };
    $('#windConceptFileChoice').change(function(e) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {
                type: 'binary'
            });
            var trade_date = null;
            windConceptUploadTableOption.data = [];
            workbook.SheetNames.forEach(function(sheetName) {
                var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                XL_row_object.forEach(function(row) {
                    if (row['证券代码']) {
                        windConceptUploadTableOption.data.push(row);
                    }
                    for (var k in row) {
                        if (k.substring(0, 6) == '所属概念板块') {
                            row['所属概念板块'] = row[k].replaceAll(';', '/');
                            trade_date = k.substring(k.length-10);
                            delete row[k];
                            break;
                        }
                    }
                    if (row['证券简称'] == undefined) {
                        windConceptUploadTableOption.data.pop();
                    }
                })
            });

            if (trade_date == null) {
                windConceptUploadTableOption.data = [];
            }
            windConceptUploadTableOption.trade_date = trade_date;

            $('#windConceptModal').modal('toggle');
            $('#windConceptModalTable').bootstrapTable('refreshOptions', windConceptUploadTableOption);
        }
        reader.onerror = function(ex) {
            console.log(ex);
        };
        reader.readAsBinaryString(e.target.files[0]);
    }); 

    var uploadWindConcept = function() {
        $.ajax({
            url: '/api/update_wind_concept_data',
            method: 'post',
            beforeSend: function (xhr, settings){
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", $('[name=csrfmiddlewaretoken]').val());
                }
            },
            contentType: 'application/json',
            data: JSON.stringify({
                'keywords': windConceptUploadTableOption.data,
                'trade_date': windConceptUploadTableOption.trade_date,
                // 'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val(),
            }),
            success: function () {
                $('#wind-concepts-table').bootstrapTable('refreshOptions', windTableOption);
                $('#windConceptFileChoice').val('');
            },
            error: function (e) {
                console.log(e);
                $('#windConceptFileChoice').val('');
            }
        });
    }

    $('#quarterSelect').change(updateUrl);
    tushareTableOption.updateUrl();
    windTableOption.updateUrl();

    $('#qcpt-table').bootstrapTable(tableOption);
    $('#qcpt-table-detail').bootstrapTable(detailTableOption);
    $('#tushare-concepts-table').bootstrapTable(tushareTableOption);
    $('#wind-concepts-table').bootstrapTable(windTableOption);
    $('#windConceptModalTable').bootstrapTable(windConceptUploadTableOption);

    $('.quarter-btn').click(function (){
        $('#quarter-dropdown').text($(this).text());
        $('#indicator-display').text($('#indicators-dropdown').val()+$('#quarter-dropdown').text());
    });

    $('#windConceptsDateSelect').change(function () {
        windTableOption.updateUrl();
        $('#wind-concepts-table').bootstrapTable('refreshOptions', windTableOption);
    });

    $('#tushareConceptsDateSelect').change(function () {
        tushareTableOption.updateUrl();
        $('#tushare-concepts-table').bootstrapTable('refreshOptions', tushareTableOption);
    });

    searchInputPopover();

</script>
{% endblock %}